from mcp.server.fastmcp import FastMCP
from typing import Any, Dict, List, Optional, Set, Tuple
import json
import os
import re
from datetime import date, datetime
from beancount.core import data, account, getters
from beancount.core.amount import Amount
from beancount.core.number import Decimal
from beancount.parser import parser, printer
from beancount.loader import load_file
import csv
import os
import json
import csv
import re
from datetime import datetime
# 假设这些是你环境中的依赖
from beancount.loader import load_file
# beancount.query模块在当前版本中不可用
# 使用beancount的核心功能替代

# 导入账户创建和交易记录功能
from account_setup_mcp import create_beancount_account
from transaction_mcp import create_transaction, validate_accounts

# 设置默认的beancount文件路径
DEFAULT_BEANCOUNT_FILE = os.path.join(os.path.dirname(__file__), "ledger.beancount")

# 创建MCP实例
mcp = FastMCP("accounting-server")

@mcp.tool()
async def say_hello(name: str) -> str:
    """向用户问好"""
    return f"你好，{name}！欢迎使用会计MCP！"

@mcp.tool()
async def get_beancount_file_path() -> str:
    """获取当前使用的beancount文件路径
    
    Returns:
        当前使用的beancount文件路径
    """
    return DEFAULT_BEANCOUNT_FILE

@mcp.tool()
async def set_beancount_file(file_path: str) -> str:
    """设置当前使用的beancount文件路径
    
    Args:
        file_path: 新的beancount文件路径
        
    Returns:
        设置结果的JSON字符串
    """
    global DEFAULT_BEANCOUNT_FILE
    
    try:
        # 检查文件是否存在
        if not os.path.exists(file_path):
            return json.dumps({
                "success": False, 
                "error": f"文件不存在: {file_path}",
                "current_file": DEFAULT_BEANCOUNT_FILE
            }, ensure_ascii=False)
        
        # 检查文件是否为有效的beancount文件
        try:
            entries, errors, _ = parser.parse_file(file_path)
            if errors:
                return json.dumps({
                    "success": False, 
                    "error": f"文件格式错误: {errors}",
                    "current_file": DEFAULT_BEANCOUNT_FILE
                }, ensure_ascii=False)
        except Exception as e:
            return json.dumps({
                "success": False, 
                "error": f"无法解析文件: {str(e)}",
                "current_file": DEFAULT_BEANCOUNT_FILE
            }, ensure_ascii=False)
        
        # 更新默认文件路径
        old_path = DEFAULT_BEANCOUNT_FILE
        DEFAULT_BEANCOUNT_FILE = file_path
        
        return json.dumps({
            "success": True, 
            "message": f"Beancount文件已切换",
            "previous_file": old_path,
            "current_file": DEFAULT_BEANCOUNT_FILE
        }, ensure_ascii=False)
    except Exception as e:
        return json.dumps({
            "success": False, 
            "error": str(e),
            "current_file": DEFAULT_BEANCOUNT_FILE
        }, ensure_ascii=False)

@mcp.tool()
async def get_accounts() -> str:
    """获取当前账本中的所有账户
    
    Returns:
        账户列表的JSON字符串
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            return json.dumps({"success": False, "error": "Beancount文件不存在，请先创建"}, ensure_ascii=False)
            
        # 加载beancount文件
        entries, errors, options_map = load_file(DEFAULT_BEANCOUNT_FILE)
        if errors:
            return json.dumps({"success": False, "error": f"账套文件存在错误: {errors}"}, ensure_ascii=False)
            
        # 获取所有已定义的账户
        accounts = getters.get_accounts(entries)
        
        # 按账户类型分组
        account_groups = {
            "Assets": [],
            "Liabilities": [],
            "Income": [],
            "Expenses": [],
            "Equity": [],
            "Other": []
        }
        
        for acc in accounts:
            parts = acc.split(':', 1)
            if len(parts) > 0:
                account_type = parts[0]
                if account_type in account_groups:
                    account_groups[account_type].append(acc)
                else:
                    account_groups["Other"].append(acc)
        
        return json.dumps({
            "success": True,
            "accounts": list(accounts),
            "account_groups": account_groups,
            "total": len(accounts)
        }, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def create_beancount_file(file_path: str = "") -> str:
    """创建一个新的beancount文件
    
    Args:
        file_path: 新文件的路径，如果为空则使用默认路径
        
    Returns:
        创建结果信息
    """
    global DEFAULT_BEANCOUNT_FILE
    
    # 如果未指定文件路径，使用默认路径
    if not file_path:
        file_path = DEFAULT_BEANCOUNT_FILE
    else:
        # 更新默认文件路径为新创建的文件
        DEFAULT_BEANCOUNT_FILE = file_path
    
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        # 创建空文件
        with open(file_path, 'w', encoding='utf-8') as f:
            pass
        
        return json.dumps({
            "success": True, 
            "message": f"空的Beancount文件已创建: {file_path}",
            "default_file_path": DEFAULT_BEANCOUNT_FILE
        }, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def initialize_ledger(business_type: str = "personal", currency: str = "CNY") -> str:
    """初始化一个新的账本，根据业务类型创建常用账户
    
    Args:
        business_type: 业务类型，可选值：personal(个人), retail(零售), service(服务), manufacturing(制造)
        currency: 默认货币类型
        
    Returns:
        初始化结果的JSON字符串
    """
    try:
        # 定义不同业务类型的账户模板
        account_templates = {
            "personal": [
                {"account_name": "Bank:Checking", "account_type": "Assets", "currency": currency},
                {"account_name": "Bank:Savings", "account_type": "Assets", "currency": currency},
                {"account_name": "Cash", "account_type": "Assets", "currency": currency},
                {"account_name": "CreditCard", "account_type": "Liabilities", "currency": currency},
                {"account_name": "Salary", "account_type": "Income", "currency": currency},
                {"account_name": "Interest", "account_type": "Income", "currency": currency},
                {"account_name": "Food", "account_type": "Expenses", "currency": currency},
                {"account_name": "Transport", "account_type": "Expenses", "currency": currency},
                {"account_name": "Utilities", "account_type": "Expenses", "currency": currency},
                {"account_name": "Entertainment", "account_type": "Expenses", "currency": currency},
                {"account_name": "Opening-Balances", "account_type": "Equity", "currency": currency}
            ],
            "retail": [
                {"account_name": "Bank:Checking", "account_type": "Assets", "currency": currency},
                {"account_name": "Bank:Savings", "account_type": "Assets", "currency": currency},
                {"account_name": "Cash:Register", "account_type": "Assets", "currency": currency},
                {"account_name": "Inventory", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Receivable", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Payable", "account_type": "Liabilities", "currency": currency},
                {"account_name": "Sales", "account_type": "Income", "currency": currency},
                {"account_name": "Sales:Returns", "account_type": "Income", "currency": currency},
                {"account_name": "COGS", "account_type": "Expenses", "currency": currency},
                {"account_name": "Rent", "account_type": "Expenses", "currency": currency},
                {"account_name": "Utilities", "account_type": "Expenses", "currency": currency},
                {"account_name": "Salaries", "account_type": "Expenses", "currency": currency},
                {"account_name": "Marketing", "account_type": "Expenses", "currency": currency},
                {"account_name": "Opening-Balances", "account_type": "Equity", "currency": currency}
            ],
            "service": [
                {"account_name": "Bank:Checking", "account_type": "Assets", "currency": currency},
                {"account_name": "Bank:Savings", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Receivable", "account_type": "Assets", "currency": currency},
                {"account_name": "Equipment", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Payable", "account_type": "Liabilities", "currency": currency},
                {"account_name": "ServiceRevenue", "account_type": "Income", "currency": currency},
                {"account_name": "Consulting", "account_type": "Income", "currency": currency},
                {"account_name": "Rent", "account_type": "Expenses", "currency": currency},
                {"account_name": "Utilities", "account_type": "Expenses", "currency": currency},
                {"account_name": "Salaries", "account_type": "Expenses", "currency": currency},
                {"account_name": "Software", "account_type": "Expenses", "currency": currency},
                {"account_name": "Travel", "account_type": "Expenses", "currency": currency},
                {"account_name": "Opening-Balances", "account_type": "Equity", "currency": currency}
            ],
            "manufacturing": [
                {"account_name": "Bank:Checking", "account_type": "Assets", "currency": currency},
                {"account_name": "Bank:Savings", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Receivable", "account_type": "Assets", "currency": currency},
                {"account_name": "Inventory:RawMaterials", "account_type": "Assets", "currency": currency},
                {"account_name": "Inventory:WorkInProgress", "account_type": "Assets", "currency": currency},
                {"account_name": "Inventory:FinishedGoods", "account_type": "Assets", "currency": currency},
                {"account_name": "Equipment:Machinery", "account_type": "Assets", "currency": currency},
                {"account_name": "Accounts:Payable", "account_type": "Liabilities", "currency": currency},
                {"account_name": "Loans:Equipment", "account_type": "Liabilities", "currency": currency},
                {"account_name": "Sales", "account_type": "Income", "currency": currency},
                {"account_name": "COGS:Materials", "account_type": "Expenses", "currency": currency},
                {"account_name": "COGS:Labor", "account_type": "Expenses", "currency": currency},
                {"account_name": "COGS:Overhead", "account_type": "Expenses", "currency": currency},
                {"account_name": "Rent:Factory", "account_type": "Expenses", "currency": currency},
                {"account_name": "Utilities:Factory", "account_type": "Expenses", "currency": currency},
                {"account_name": "Salaries:Production", "account_type": "Expenses", "currency": currency},
                {"account_name": "Salaries:Administrative", "account_type": "Expenses", "currency": currency},
                {"account_name": "Maintenance", "account_type": "Expenses", "currency": currency},
                {"account_name": "Opening-Balances", "account_type": "Equity", "currency": currency}
            ]
        }
        
        # 检查业务类型是否有效
        if business_type not in account_templates:
            return json.dumps({
                "success": False,
                "error": f"无效的业务类型: {business_type}，可用类型: {', '.join(account_templates.keys())}"
            }, ensure_ascii=False)
        
        # 创建beancount文件（如果不存在）
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            content = f"""; 这是一个beancount账本文件
; 创建日期: {date.today().isoformat()}

option "title" "我的{business_type}账本"
option "operating_currency" "{currency}"

"""
            with open(DEFAULT_BEANCOUNT_FILE, 'w', encoding='utf-8') as f:
                f.write(content)
        
        # 批量创建账户
        accounts_to_create = account_templates[business_type]
        result = await create_accounts(accounts_to_create)
        result_data = json.loads(result)
        
        # 添加业务类型信息
        result_data["business_type"] = business_type
        result_data["ledger_file"] = DEFAULT_BEANCOUNT_FILE
        
        return json.dumps(result_data, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)
    if not content:
        content = """"; 这是一个beancount账本文件
; 创建日期: {}

option "title" "我的个人账本"
option "operating_currency" "CNY"

; 定义账户
2024-01-01 open Assets:Bank:Checking       CNY
2024-01-01 open Assets:Cash                 CNY
2024-01-01 open Income:Salary               CNY
2024-01-01 open Expenses:Food               CNY
2024-01-01 open Expenses:Transport          CNY
2024-01-01 open Expenses:Utilities          CNY
2024-01-01 open Expenses:Entertainment      CNY
2024-01-01 open Liabilities:CreditCard      CNY
""".format(date.today().isoformat())
    
    try:
        with open(DEFAULT_BEANCOUNT_FILE, 'w', encoding='utf-8') as f:
            f.write(content)
        return json.dumps({"success": True, "message": f"Beancount文件已创建: {DEFAULT_BEANCOUNT_FILE}"})
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def add_transaction(date_str: str, narration: str, payee: str, 
                        from_account: str, to_account: str, 
                        amount: str, currency: str = "CNY") -> str:
    """添加一笔简单交易到beancount文件
    
    Args:
        date_str: 交易日期，格式为YYYY-MM-DD
        narration: 交易描述
        payee: 交易对方
        from_account: 支出账户
        to_account: 收入账户
        amount: 金额
        currency: 货币，默认为CNY
        
    Returns:
        添加结果信息
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            return json.dumps({"success": False, "error": "Beancount文件不存在，请先创建"}, ensure_ascii=False)
        
        # 构建交易记录
        transaction = f"""
{date_str} * "{payee}" "{narration}"
    {from_account}  -{amount} {currency}
    {to_account}
"""
        
        # 追加到文件
        with open(DEFAULT_BEANCOUNT_FILE, 'a', encoding='utf-8') as f:
            f.write(transaction)
            
        return json.dumps({
            "success": True, 
            "message": f"交易已添加", 
            "transaction": transaction.strip()
        }, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def create_complex_transaction(date: str, description: str, postings: List[Tuple[str, float, str]], 
                                   narration: str = "", tags: List[str] = None, auto_create_accounts: bool = False) -> str:
    """创建一个复杂的会计凭证（交易记录）并写入文件
    
    Args:
        date: 交易日期，格式 YYYY-MM-DD
        description: 交易描述
        postings: 会计分录列表，每个分录为(账户名, 金额, 货币)的元组
        narration: 详细说明
        tags: 标签列表
        auto_create_accounts: 是否自动创建缺失的账户
        
    Returns:
        创建结果的JSON字符串
    """
    try:
        # 验证科目是否存在
        is_valid, error_message, existing_accounts = validate_accounts(postings, DEFAULT_BEANCOUNT_FILE)
        
        # 如果有缺失账户且允许自动创建
        if not is_valid and auto_create_accounts:
            missing_accounts = []
            for account, _, currency in postings:
                if account not in existing_accounts:
                    missing_accounts.append((account, currency))
            
            # 自动创建缺失账户
            created_accounts = []
            for account, currency in missing_accounts:
                # 从完整账户名中提取账户类型和名称
                parts = account.split(':', 1)
                if len(parts) == 2:
                    account_type, account_name = parts
                    # 创建账户
                    result = create_beancount_account(account_name, account_type, currency, date, DEFAULT_BEANCOUNT_FILE)
                    created_accounts.append(result)
            
            # 重新验证账户
            is_valid, error_message, existing_accounts = validate_accounts(postings, DEFAULT_BEANCOUNT_FILE)
            
            # 如果自动创建了账户，添加到结果中
            if created_accounts:
                auto_created_info = {
                    "auto_created": True,
                    "created_accounts": created_accounts
                }
            else:
                auto_created_info = {"auto_created": False}
        
        # 如果账户验证失败
        if not is_valid:
            missing_accounts = []
            for account, _, currency in postings:
                if account not in existing_accounts:
                    missing_accounts.append((account, currency))
            
            result = {
                "success": False,
                "error": error_message,
                "existing_accounts": existing_accounts,
                "missing_accounts": missing_accounts,
                "auto_create_attempted": auto_create_accounts
            }
            
            # 如果尝试了自动创建，添加创建结果
            if auto_create_accounts:
                result.update(auto_created_info)
                
            return json.dumps(result)
        
        # 创建交易
        tag_set = set(tags) if tags else set()
        result = create_transaction(date, description, postings, DEFAULT_BEANCOUNT_FILE, narration, tag_set)
        
        return json.dumps(result)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def query_beancount(query_string: str) -> str:
    """执行beancount查询语言(BQL)查询
    
    Args:
        query_string: BQL查询语句
        
    Returns:
        查询结果的JSON字符串
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            return json.dumps({"success": False, "error": "Beancount文件不存在，请先创建"}, ensure_ascii=False)
            
        # 加载beancount文件
        entries, errors, options_map = parser.parse_file(DEFAULT_BEANCOUNT_FILE)
        if errors:
            return json.dumps({"success": False, "error": str(errors)}, ensure_ascii=False)
            
        # 由于beancount.query模块不可用，我们使用简化的查询实现
        # 解析查询字符串
        result = []
        
        # 提取查询类型和条件
        select_match = re.search(r'SELECT\s+([^\s]+)(?:\s*,\s*([^\s]+))*\s+WHERE\s+(.*)', query_string, re.IGNORECASE)
        if select_match:
            # 提取要选择的字段
            fields = [select_match.group(1)]
            if select_match.group(2):
                fields.extend(re.findall(r'([^\s,]+)', select_match.group(2)))
            
            # 提取条件
            condition = select_match.group(3)
            
            # 根据条件过滤entries
            filtered_entries = []
            for entry in entries:
                # 只处理Transaction类型
                if isinstance(entry, data.Transaction):
                    # 简单条件匹配
                    if 'account' in condition:
                        account_match = re.search(r'account\s*[=~]\s*"([^"]+)"', condition)
                        if account_match:
                            account_pattern = account_match.group(1)
                            # 检查交易中的任何一个账户是否匹配
                            for posting in entry.postings:
                                if (account_pattern.startswith('^') and 
                                    re.match(account_pattern, posting.account)) or \
                                   (not account_pattern.startswith('^') and 
                                    re.search(account_pattern, posting.account)):
                                    filtered_entries.append(entry)
                                    break
            
            # 构建结果
            for entry in filtered_entries:
                for posting in entry.postings:
                    row_dict = {}
                    for field in fields:
                        if field == 'account':
                            row_dict['account'] = posting.account
                        elif field == 'date':
                            row_dict['date'] = str(entry.date)
                        elif field == 'position':
                            row_dict['position'] = str(posting.units)
                        elif field == 'narration':
                            row_dict['narration'] = entry.narration
                        elif field == 'payee':
                            row_dict['payee'] = entry.payee or ''
                        elif field == 'flag':
                            row_dict['flag'] = entry.flag
                        elif field.startswith('sum('):
                            # 简化的sum实现
                            if 'position' in field:
                                # 按账户分组汇总金额
                                account_sums = {}
                                for e in filtered_entries:
                                    for p in e.postings:
                                        if p.account not in account_sums:
                                            account_sums[p.account] = []
                                        account_sums[p.account].append(p.units)
                                
                                # 只返回当前账户的汇总
                                if posting.account in account_sums:
                                    # 简化处理，只返回字符串形式
                                    row_dict['sum(position)'] = str(account_sums[posting.account])
                    
                    if row_dict:  # 只添加非空结果
                        result.append(row_dict)
        
        return json.dumps({"success": True, "result": result}, indent=2, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def get_account_balance(account: str = None) -> str:
    """获取指定账户或所有账户的余额
    
    Args:
        account: 账户名称，如果为空则返回所有账户余额
        
    Returns:
        账户余额的JSON字符串
    """
    try:
        # 构建查询
        if account:
            query_string = f'SELECT account, sum(position) WHERE account = "{account}"'
        else:
            query_string = 'SELECT account, sum(position) WHERE account ~ "Assets|Liabilities"'
            
        return await query_beancount(query_string)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def get_income_statement(start_date: str = None, end_date: str = None) -> str:
    """获取收入报表
    
    Args:
        start_date: 开始日期，格式为YYYY-MM-DD，如果为空则从最早记录开始
        end_date: 结束日期，格式为YYYY-MM-DD，如果为空则到最新记录结束
        
    Returns:
        收入报表的JSON字符串
    """
    try:
        # 构建日期条件
        date_condition = ""
        if start_date:
            date_condition += f' AND date >= {start_date}'
        if end_date:
            date_condition += f' AND date <= {end_date}'
            
        # 收入查询
        income_query = f'SELECT account, sum(position) WHERE account ~ "Income"{date_condition}'
        
        # 支出查询
        expense_query = f'SELECT account, sum(position) WHERE account ~ "Expenses"{date_condition}'
        
        # 执行查询
        income_result = json.loads(await query_beancount(income_query))
        expense_result = json.loads(await query_beancount(expense_query))
        
        # 合并结果
        return json.dumps({
            "success": True,
            "income": income_result.get("result", []),
            "expenses": expense_result.get("result", []),
            "period": {
                "start_date": start_date or "earliest",
                "end_date": end_date or "latest"
            }
        }, indent=2, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def get_transaction_history(account: str = None, limit: int = 10) -> str:
    """获取交易历史
    
    Args:
        account: 账户名称，如果为空则返回所有账户的交易
        limit: 返回的交易数量限制
        
    Returns:
        交易历史的JSON字符串
    """
    try:
        # 构建查询
        account_condition = f' AND account ~ "{account}"' if account else ''
        query_string = f'SELECT date, flag, narration, payee, account, position WHERE TRUE{account_condition} ORDER BY date DESC LIMIT {limit}'
            
        return await query_beancount(query_string)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def get_accounts_list() -> str:
    """获取所有账户列表
    
    Returns:
        账户列表的JSON字符串
    """
    try:
        query_string = 'SELECT DISTINCT account ORDER BY account'
        return await query_beancount(query_string)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def validate_beancount_file() -> str:
    """验证beancount文件的有效性
    
    Returns:
        验证结果的JSON字符串
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            return json.dumps({"success": False, "error": "Beancount文件不存在，请先创建"}, ensure_ascii=False)
            
        # 加载beancount文件
        entries, errors, options_map = parser.parse_file(DEFAULT_BEANCOUNT_FILE)
        
        if errors:
            error_messages = [str(error) for error in errors]
            return json.dumps({"success": False, "errors": error_messages})
        else:
            return json.dumps({"success": True, "message": "Beancount文件验证通过"})
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def create_account(account_name: str, account_type: str, currency: str = "CNY", start_date: str = None) -> str:
    """创建一个新的beancount账户
    
    Args:
        account_name: 账户名称，格式为'部门:具体账户'（不包含账户类型前缀）
        account_type: 账户类型 (Assets, Liabilities, Income, Expenses)
        currency: 货币类型，默认为CNY
        start_date: 开始日期，格式为YYYY-MM-DD，如果为空则使用当前年份的1月1日
        
    Returns:
        创建结果的JSON字符串
    """
    try:
        result = create_beancount_account(account_name, account_type, currency, start_date, DEFAULT_BEANCOUNT_FILE)
        return json.dumps(result)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

@mcp.tool()
async def create_accounts(accounts: List[Dict[str, str]]) -> str:
    """批量创建多个beancount账户
    
    Args:
        accounts: 账户列表，每个账户包含以下字段：
            - account_name: 账户名称，格式为'部门:具体账户'（不包含账户类型前缀）
            - account_type: 账户类型 (Assets, Liabilities, Income, Expenses)
            - currency: 货币类型，默认为CNY
            - start_date: 开始日期，格式为YYYY-MM-DD，如果为空则使用当前年份的1月1日
        
    Returns:
        创建结果的JSON字符串
    """
    results = []
    for account_info in accounts:
        try:
            account_name = account_info.get("account_name")
            account_type = account_info.get("account_type")
            currency = account_info.get("currency", "CNY")
            start_date = account_info.get("start_date")
            
            if not account_name or not account_type:
                results.append({
                    "success": False,
                    "error": "账户名称和类型不能为空",
                    "account_info": account_info
                })
                continue
                
            result = create_beancount_account(account_name, account_type, currency, start_date, DEFAULT_BEANCOUNT_FILE)
            result["account_info"] = account_info
            results.append(result)
        except Exception as e:
            results.append({
                "success": False,
                "error": str(e),
                "account_info": account_info
            })
    
    return json.dumps({
        "success": True,
        "results": results,
        "total": len(accounts),
        "success_count": sum(1 for r in results if r.get("success", False))
    }, ensure_ascii=False)

@mcp.tool()
async def update_transaction(date_str: str, old_narration: str, new_narration: str, 
                             new_payee: str, new_from_account: str, new_to_account: str, 
                             new_amount: str, currency: str = "CNY") -> str:
    """更新现有的交易记录
    
    Args:
        date_str: 交易日期，格式为YYYY-MM-DD
        old_narration: 原交易描述，用于定位交易
        new_narration: 新的交易描述
        new_payee: 新的交易对方
        new_from_account: 新的支出账户
        new_to_account: 新的收入账户
        new_amount: 新的金额
        currency: 货币，默认为CNY
        
    Returns:
        更新结果信息
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(DEFAULT_BEANCOUNT_FILE):
            return json.dumps({"success": False, "error": "Beancount文件不存在，请先创建"}, ensure_ascii=False)
        
        # 读取文件内容
        with open(DEFAULT_BEANCOUNT_FILE, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 查找并更新交易记录
        updated = False
        for i, line in enumerate(lines):
            if date_str in line and old_narration in line:
                # 更新交易记录
                lines[i] = f'{date_str} * "{new_payee}" "{new_narration}"\n'
                lines[i+1] = f'    {new_from_account}  -{new_amount} {currency}\n'
                lines[i+2] = f'    {new_to_account}\n'
                updated = True
                break
        
        # 写回文件
        if updated:
            with open(DEFAULT_BEANCOUNT_FILE, 'w', encoding='utf-8') as f:
                f.writelines(lines)
            return json.dumps({"success": True, "message": "交易已更新"}, ensure_ascii=False)
        else:
            return json.dumps({"success": False, "error": "未找到匹配的交易记录"}, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)

if __name__ == "__main__":
    # 设置JSON序列化默认参数，确保中文不会被转义为Unicode编码
    json._default_encoder.ensure_ascii = False
    mcp.run(transport="stdio")
    # mcp.run(transport="sse")